package com.sun.dream.fish.mvc;

import com.sun.dream.fish.util.ResponseUtil;
import com.sun.dream.fish.vo.PageResultVO;
import com.sun.dream.fish.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Map;

/**
 * Description:  全局接口返回值统一处理
 * Created By ljl on 2023/12/04.
 */
@RestControllerAdvice
@Slf4j
public class GlobalResponseBodyAdvice implements ResponseBodyAdvice<Object> {


    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof ResultVO) {
            ResultVO resultVO = (ResultVO) body;
            if (resultVO.getCode() == 1000) {
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
            } else if (resultVO.getCode() == 403) {
                response.setStatusCode(HttpStatus.FORBIDDEN);
            }
            return body;
        }

        if (body instanceof PageResultVO) {
            PageResultVO resultVO = (PageResultVO) body;
            if (resultVO.getCode() == 1000) {
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
            } else if (resultVO.getCode() == 403) {
                response.setStatusCode(HttpStatus.FORBIDDEN);
            }
            return body;
        }

        //响应的是资源数据,则直接返回
        if (body instanceof Resource) {
            return body;
        }

        if (body instanceof Map && ((ServletServerHttpResponse) response).getServletResponse().getStatus() == HttpStatus.OK.value()) {
            return ResponseUtil.ok(body);
        }

        if (body instanceof Map) {
            return ResponseUtil.fail(body, "请求错误");
        }

        //返回的是空数据,但是响应为200则返回ok响应数据报文
        if (body == null && ((ServletServerHttpResponse) response).getServletResponse().getStatus() == HttpStatus.OK.value()) {
            return ResponseUtil.ok();
        }

        //非200响应数据为空时,则直接返回空
        if (body == null) {
            return null;
        }
        throw new IllegalArgumentException("不支持的返回数据类型 :" + body.getClass().getName());
    }
}
